package com.cz.zslu.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.cz.zslu.common.ReturnObject;
import com.cz.zslu.entity.*;
import com.cz.zslu.interceptor.BaseContextHandler;
import com.cz.zslu.interceptor.IgnoreAuth;
import com.cz.zslu.model.StatisticsInfo;
import com.cz.zslu.rest.BaseController;
import com.cz.zslu.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * 店铺管理 前端控制器
 * </p>
 *
 * @author 森森
 */
@RestController
@RequestMapping("/sys/store")
@Api(description = "店铺管理")
public class StoreController extends BaseController<IZslStoreService, ZslStore> {

    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private IZslFollowService iZslFollowService;
    @Autowired
    private IZslBrowseHistoryService iZslBrowseHistoryService;
    @Autowired
    private IOriginAuthorizationService iOriginAuthorizationService;
    @Autowired
    private IZslOriginService iZslOriginService;
    @Autowired
    private IZslStoreCommodityService iZslStoreCommodityService;
    @Autowired
    private IZslStoreService iZslStoreService;
    @Autowired
    private OnlineIMService onlineIMService;


    @IgnoreAuth
    @ApiOperation("获取全部店铺分页")
    @RequestMapping(value = "/getPage", method = RequestMethod.POST)
    public ReturnObject<List<ZslStore>> getPage(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                                @ApiParam("店铺名称") String name) {
        EntityWrapper<ZslStore> ew = new EntityWrapper<>();
        if (StringUtils.isNotBlank(name)) {

            ew.andNew().like("name", name).or().like("phone", name);
        }
        ew.orderBy("crt_time", false);
        Page<ZslStore> obj = baseService.selectPage(new Page<>(offset, limit), ew);
        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), obj.getRecords());
    }


    @ApiOperation("新增或编辑店铺")
    @RequestMapping(value = "/addInfo", method = RequestMethod.POST)
    public ReturnObject<ZslStore> addInfo(@ApiParam("商铺名称") String name,
                                          @ApiParam("是否显示号码（0：显示，1：隐藏）") Integer showPhone,
                                          @ApiParam("是否显示自定义树（0：显示，1：隐藏）") Integer showTree) {
        SysUser sysUser = iSysUserService.selectById(BaseContextHandler.getUserID());
        ZslStore info;
        if (sysUser.getStoreId() == null) {
            info = new ZslStore();
        } else {
            info = baseService.selectById(sysUser.getStoreId());
        }
        info.setName(name);
        info.setShowPhone(showPhone);
        info.setShowTree(showTree);
        if (info.getId() == null) {
            baseService.insert(info);
        } else {
            baseService.updateById(info);
        }
        sysUser.setStoreId(info.getId());
        sysUser.setStoreName(name);
        iSysUserService.updateById(sysUser);
        return new ReturnObject<>(0, "获取成功");
    }


    @IgnoreAuth
    @ApiOperation("查看店铺信息")
    @RequestMapping(value = "/view", method = RequestMethod.POST)
    public ReturnObject<ZslStore> view(@ApiParam("id") @RequestParam Long id, @ApiParam("是否登录 0、登录 传空表示未登录") @RequestParam Integer type) {
        ZslStore info = baseService.selectById(id);
        info.setEntName(iSysUserService.selectOne(new EntityWrapper<SysUser>().eq("store_id", id)).getCompanyName());
        info.setFocus(0);
        if (type != null) {
            if (iZslFollowService.selectCount(new EntityWrapper<ZslFollow>().eq("user_id",
                    BaseContextHandler.getUserID()).eq("store_id", id)) > 0) {
                info.setFocus(1);
            }
        }
        return new ReturnObject<>(0, "获取成功", info);
    }


    @ApiOperation("获取店铺统计信息")
    @RequestMapping(value = "/statistics", method = RequestMethod.POST)
    public ReturnObject<StatisticsInfo> statistics() {
        SysUser sysUser = iSysUserService.selectById(BaseContextHandler.getUserID());
        StatisticsInfo statisticsInfo = new StatisticsInfo();
//        statisticsInfo.
        //产品浏览数
        statisticsInfo.setPageViews(iZslBrowseHistoryService.selectCount(new EntityWrapper<ZslBrowseHistory>().eq(
                "store_id",
                sysUser.getStoreId())));
        //店铺关注数
        statisticsInfo.setStoreFollow(iZslFollowService.selectCount(new EntityWrapper<ZslFollow>().eq("store_id",
                sysUser.getStoreId())));
        //授权品牌
        List<Object> ids = iOriginAuthorizationService.selectObjs(new EntityWrapper<OriginAuthorization>().eq(
                "store_id", sysUser.getStoreId()).eq("status", 1).setSqlSelect("origin_id"));
        statisticsInfo.setOrigins(iZslOriginService.selectList(new EntityWrapper<ZslOrigin>().in("id", ids)));
        //上架商品
        statisticsInfo.setOnOffer(iZslStoreCommodityService.selectCount(new EntityWrapper<ZslStoreCommodity>().eq(
                "user_id", BaseContextHandler.getUserID()).eq("state", 0)));
        //下架商品
        statisticsInfo.setUndercarriage(iZslStoreCommodityService.selectCount(new EntityWrapper<ZslStoreCommodity>().eq(
                "user_id", BaseContextHandler.getUserID()).eq("state", 1)));

        return new ReturnObject<>(0, "获取成功", statisticsInfo);
    }


    @ApiOperation("管理后台获取所有店铺")
    @IgnoreAuth
    @RequestMapping(value = "/getAllStores", method = RequestMethod.POST)
    public ReturnObject<List<ZslStore>> getAllStores(@ApiParam("name") String name) {
        EntityWrapper<ZslStore> ew = new EntityWrapper<>();
//        ew.eq("state", 0);
        if (StringUtils.isNotBlank(name)) {

            ew.like("name", name);
        }
        ew.orderBy("crt_time", false);
        return new ReturnObject<>(0, "获取成功", baseService.selectList(ew));
    }

    @ApiOperation("管理后台对店铺对 禁用/恢复")
    @IgnoreAuth
    @RequestMapping(value = "/forbidden", method = RequestMethod.POST)
    public ReturnObject<ZslStore> deal(@ApiParam("id") @RequestParam Long id,
                                       @ApiParam("state 0、恢复 1、禁用") @RequestParam Integer state,
                                       @ApiParam("replyContent 禁用原因") @RequestParam String replyContent) {
        ZslStore info = baseService.selectById(id);
        info.setState(state);
        baseService.updateById(info);
        if(state==1){
            //对店铺中对所有产品进行下架
            List<ZslStoreCommodity> zslStoreCommodityList =
                    iZslStoreCommodityService.selectList(new EntityWrapper<ZslStoreCommodity>()
                            .eq("state", 0).eq("status", 0)
                            .eq("store_id", id));
            if(zslStoreCommodityList!=null&&zslStoreCommodityList.size()>0){
                for (int i = 0; i <zslStoreCommodityList.size() ; i++) {
                    iZslStoreCommodityService.updateById(zslStoreCommodityList.get(i).setState(1));
                }
            }
            //发送禁用原因给商铺
            SysUser fromUser=
                    iSysUserService.selectById(BaseContextHandler.getUserID());
            SysUser toUser =
                    iSysUserService.selectOne(new EntityWrapper<SysUser>().eq(
                            "store_id",id));
            OnlineIM im = new OnlineIM();
            im.setType(5);
            im.setName(fromUser.getUsername());
            im.setContent(replyContent);
            im.setPhone(fromUser.getPhone());
//            im.setQq(fromUser.getQq());
            im.setFromUserId(fromUser.getId());
            im.setUserId(toUser.getId());
            im.setIsDeal(1);
            im.setHeadPic(fromUser.getHeadPortraits());
            im.setStoreId(id);
            ZslStore store = baseService.selectById(id);
            im.setStoreName(store.getName());
            onlineIMService.insert(im);
        }
        return new ReturnObject<>(0, "操作成功");
    }

    @IgnoreAuth
    @ApiOperation("管理后台查看店铺信息")
    @RequestMapping(value = "/backgroudview", method = RequestMethod.POST)
    public ReturnObject<ZslStore> backgroudview(@ApiParam("id") @RequestParam Long id) {
        ZslStore info = iZslStoreService.selectById(id);
        return new ReturnObject<>(0, "获取成功", info);
    }

}

